package com.example.kotlineventtracker.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.kotlineventtracker.model.PageEvent
import com.example.kotlineventtracker.model.PageEventRequestBody
import com.example.kotlineventtracker.util.EventRepository
import kotlinx.coroutines.launch

class EventViewModel(application: Application) : AndroidViewModel(application) {
//    private lateinit var repository: EventRepository
//    // 设置 repository
//    fun setRepository(repository: EventRepository) {
//        this.repository = repository
//    }
     //获取 EventRepository 的单例实例
    private val repository: EventRepository = EventRepository.getInstance(application.applicationContext)



    private val _events = MutableLiveData<List<PageEvent>>()
    val events: LiveData<List<PageEvent>> get() = _events

    fun loadEvents(type: String, searchKey: String) {
        // 设置请求body
        var request: PageEventRequestBody? = null
        if (type == "page") {
            request = PageEventRequestBody(
                eventType = listOf("page"),
                categoryId = listOf("ecoexpress"),
                searchKey = searchKey,
                pageNum = "1",
                pageSize = "20"
            )
        } else if (type == "module") {
            request = PageEventRequestBody(
                eventType = listOf("module"),
                categoryId = listOf("ecoexpress"),
                searchKey = searchKey,
                pageNum = "1",
                pageSize = "20"
            )
        } else {
            return
        }

        viewModelScope.launch {
            try {
                repository.fetchPageEvents(
                    request,
                    onSuccess = { pointResponse ->
                        if (pointResponse != null && pointResponse.data != null) {
                            // 过滤其他页面的module
                            if (type == "module") {
                                val filteredEvents = pointResponse.data.filter { it.pageDesc == searchKey }
                                _events.value = filteredEvents
                            } else {
                                _events.value = pointResponse.data
                            }
                        } else {
                            _events.value = emptyList()
                        }
                    },
                    onFailure = { throwable ->
                        throwable.printStackTrace()
                        _events.value = emptyList()
                    }
                )
            } catch (e: Exception) {
                e.printStackTrace()
                _events.value = emptyList()
            }
        }
    }
}
